package com.haha.http.rpc.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haha.http.rpc.common.exception.RpcCommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.TimeZone;

/**
 * @AUTHOR zhangxiaofan07
 * @CREATE 2022-02-09 19:45
 */
@Deprecated
public class JsonUtil {

    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final RpcCommonException JSON_TRANSFER_ERROR = new RpcCommonException("JSON_TRANSFER_ERROR", "JSON转换异常");

    static {
        MAPPER.setTimeZone(TimeZone.getDefault());
        //在反序列化时忽略在JSON字符串中存在，而在Java中不存在的属性
        MAPPER.disable((DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
        MAPPER.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
    }

    /**
     * 将对象转换成json字符串。
     *
     * @param data
     * @return
     */
    public static String toJson(Object data) {
        try {
            return MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            LogUtils.error(log, "obj transfer to json error!", e);
            throw JSON_TRANSFER_ERROR;
        }
    }

    /**
     * 将json结果集转化为对象
     *
     * @param jsonData json数据
     * @param beanType 对象中的object类型
     * @return
     */
    public static <T> T toObject(String jsonData, Class<T> beanType) {
        try {
            return MAPPER.readValue(jsonData, beanType);
        } catch (Exception e) {
            LogUtils.error(log, "json transfer to pojo error!", e);
            throw JSON_TRANSFER_ERROR;
        }
    }

    /**
     * 将json结果集转化为对象
     *
     * @param jsonData      json数据
     * @param typeReference 对象中的object类型
     * @return
     */
    public static <T> T toObject(String jsonData, TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(jsonData, typeReference);
        } catch (Exception e) {
            LogUtils.error(log, "json transfer to pojo error!", e);
            throw JSON_TRANSFER_ERROR;
        }
    }

    /**
     * 将json数据转换成pojo对象list
     *
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> toList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            return MAPPER.readValue(jsonData, javaType);
        } catch (Exception e) {
            LogUtils.error(log, "json transfer to list error!", e);
            throw JSON_TRANSFER_ERROR;
        }
    }

}
